//
//  ThreeTableViewCell.m
//  fp
//
//  Created by xingshuai on 2020/11/10.
//

#import "ThreeTableViewCell.h"

#import "FeedImgCollectionViewCell.h"
#import <PhotosUI/PhotosUI.h>             // iOS14选择图片

static NSString *identifier = @"XAFeedCollectCellID";
#import <AliyunOSSiOS/AliyunOSSiOS.h>     // 上传图片到阿里服务器头文件

#define add_img [UIImage imageNamed:@"feed_add"]
NSString * const AccessKey = @"LTAI4GKTct1qAwyKKoATfNUs";
NSString * const SecretKey = @"BkvVjMcoV7jrZ3ZtnN9KNsmLd5Vhd1";
NSString * const bucketName = @"dongfanglong-pic";

@interface ThreeTableViewCell () <UICollectionViewDelegate,UICollectionViewDataSource,ClickDeleteFeedImageDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,PHPickerViewControllerDelegate>
@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) NSMutableArray *arrImgList;      // 反馈图片数组
@property (nonatomic, strong) NSData *imageData;
@property (nonatomic, strong) NSMutableArray *selectImgList;   // 添加反馈图片
@property(nonatomic,strong) OSSClient * client;


@end

@implementation ThreeTableViewCell

+ (instancetype)cellWithTableView:(UITableView *)tableView  {
    static NSString *identifier = @"XAFeedImgCellID";
    id cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[self alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self creatViewUI];
    }
    return self;
}

-(NSMutableArray *)arrImgList {
    if (!_arrImgList) {
        _arrImgList = [NSMutableArray arrayWithObjects:add_img, nil];
    }
    return _arrImgList;
}

-(NSMutableArray *)selectImgList {
    if (!_selectImgList) {
        _selectImgList = [NSMutableArray array];
    }
    return _selectImgList;
}

-(void)creatViewUI {
    [self.contentView addSubview:self.collection];
    [self.collection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.contentView).offset(15);
        make.right.equalTo(self.contentView).offset(-15);
        make.bottom.equalTo(self.contentView).offset(-20);
    }];
}

- (UICollectionView *)collection {
    if (!_collection) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat picWidth = 90;
        flowLayout.itemSize = CGSizeMake(picWidth, picWidth);
        flowLayout.minimumLineSpacing = 10;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; // 水平方向滑动
        
        _collection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collection.backgroundColor = [UIColor colorWithHexString:@"#FFFFFF"];
        [_collection registerClass:[FeedImgCollectionViewCell class] forCellWithReuseIdentifier:identifier];
        _collection.dataSource = self;
        _collection.delegate = self;
        _collection.showsHorizontalScrollIndicator = NO;
    }
    return _collection;
}

#pragma mark - UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.arrImgList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    FeedImgCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.delegate = self;
    [cell reloadCellImg:[self.arrImgList objectAtIndex:indexPath.row] index:indexPath.row totalCount:self.arrImgList.count];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    // 如果点击的最后一个图片是add_img才添加图片
    if (indexPath.row == self.arrImgList.count-1) {
        if ([self.arrImgList containsObject:add_img]) {
            [self clickSelectAlbumImg];
        }
    }
}

// 相册
-(void)clickSelectAlbumImg {
    // 以下 API 仅为 iOS14 only
    if (@available(iOS 14, *)) {
        PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] init];
        configuration.filter = [PHPickerFilter imagesFilter]; // 可配置查询用户相册中文件的类型，支持三种
        configuration.selectionLimit = 1; // 默认为1，为0时表示可多选。

        PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:configuration];
        picker.delegate = self;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [kKeyWindow.rootViewController presentViewController:picker animated:YES completion:nil];
    } else {
        // IOS other versions
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
        picker.allowsEditing = YES;
        picker.delegate = self;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [kKeyWindow.rootViewController presentViewController:picker animated:YES completion:nil];
    }
}

#pragma mark -- ios14相册图片选择代理
-(void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results  API_AVAILABLE(ios(14)){
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (!results || !results.count) {
        return;
    }
    NSItemProvider *itemProvider = results.firstObject.itemProvider;
    if ([itemProvider canLoadObjectOfClass:UIImage.class]) {
        //MJWeakSelf
        [itemProvider loadObjectOfClass:UIImage.class completionHandler:^(__kindof id<NSItemProviderReading>  _Nullable object, NSError * _Nullable error) {
            if ([object isKindOfClass:UIImage.class]) {
                //__strong typeof(self) strongSelf = weakSelf;
                UIImage *selectImg = (UIImage *)object;
                // 获取图片大小（MB）
                NSData *imgData = UIImageJPEGRepresentation(selectImg, 1);
                CGFloat stringMB = [[self bytesToAvaiUnit:[imgData length]] floatValue];
                // 图片大于5M压缩一下
                NSNumber *totalPriceNumber = [NSNumber numberWithFloat:5.0];
                NSNumber *minPriceNumber = [NSNumber numberWithFloat:stringMB];
                if ([minPriceNumber compare:totalPriceNumber] == NSOrderedDescending || NSOrderedSame) {
                    self.imageData = UIImageJPEGRepresentation(selectImg, 0.3);
                    selectImg = [UIImage imageWithData:self.imageData];
                } else {
                    self.imageData = UIImageJPEGRepresentation(selectImg, 1);
                }
                // 上传图片获路径
                [self upLoadOssuRLImgData:self.imageData curImage:selectImg];
//                [self.arrImgList insertObject:selectImg atIndex:self.arrImgList.count-1];
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    // 非主线程，将UI操作切换到主线程进行
//                    [self.collection reloadData];
//                });
            } else {
                //[XAAlertView toast:@"请选择图片上传"];
            }
        }];
    }
}

//iOS14以下上传图片的协议与代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [kKeyWindow.rootViewController dismissViewControllerAnimated:YES completion:nil];
//    [self.arrImgList insertObject:image atIndex:self.arrImgList.count-1];
//    [self.collection reloadData];
    // 判断当前上传的图片还是视频
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]) {
        // 获取图片大小（MB）
        NSData *imgData = UIImageJPEGRepresentation(image, 1);
        CGFloat stringMB = [[self bytesToAvaiUnit:[imgData length]] floatValue];
        // 图片大于5M压缩一下
        NSNumber *totalPriceNumber = [NSNumber numberWithFloat:5.0];
        NSNumber *minPriceNumber = [NSNumber numberWithFloat:stringMB];
        if ([minPriceNumber compare:totalPriceNumber] == NSOrderedDescending || NSOrderedSame) {
            self.imageData = UIImageJPEGRepresentation(image, 0.3);
            image = [UIImage imageWithData:self.imageData];
        } else {
            self.imageData = UIImageJPEGRepresentation(image, 1);
        }
        // 上传图片获路径
        [self upLoadOssuRLImgData:self.imageData curImage:image];
    } else {
        //[XAAlertView toast:@"请选择图片上传"];
    }
}

// 获取图片大小（MB）
-(NSString *)bytesToAvaiUnit:(int64_t)bytes {
    return [NSString stringWithFormat:@"%.2lf", (double)bytes / (1024 * 1024)];
}

// 上传图片到阿里云获取图片路径
-(void)upLoadOssuRLImgData:(NSData *)selectImgData curImage:(UIImage *)image {
    NSString *objectKey = [NSString stringWithFormat:@"feedbackpic/%@.jpeg",[self uuidString]];
    NSString *endpoint = @"bp-image.bestv.com.cn";
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey secretKey:SecretKey];
    self.client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    // 配置必填字段，其中bucketName为存储空间名称；objectKey等同于objectName，表示将文件上传到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
    put.bucketName = bucketName;
    put.objectKey = objectKey;
    // put.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"];
    put.uploadingData = selectImgData; // 直接上传NSData
    // 配置可选字段,上传进度
     put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
         //指定当前上传长度、当前已经上传总长度、待上传的总长度。
         NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
     };
    // 配置可选字段。
    // put.contentType = @"";
    // put.contentMd5 = @"";
    // put.contentEncoding = @"";
    // put.contentDisposition = @"";
    // 可以在上传文件时设置元信息或者HTTP头部。
    // put.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil];
    OSSTask * putTask = [self.client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        task = [self.client presignPublicURLWithBucketName:bucketName withObjectKey:objectKey];
        if (!task.error) {
            OSSPutObjectResult * result = task.result;
            NSLog(@"upload object success url = %@",result);
            // 添加展示的图片
            [self.arrImgList insertObject:image atIndex:self.arrImgList.count-1];
            // 添加图片路径
            [self.selectImgList addObject:result];
            if (self.selectImgList.count > 0) {
                if (self.didSelectFeedImageListBlock) {
                    self.didSelectFeedImageListBlock(self.selectImgList);
                }
            }
            // 当前已展示4张图片则隐藏上传图片的按钮，否则显示上传图片的按钮
            if (self.selectImgList.count >= 4) {
                [self.arrImgList removeLastObject];
            } else {
                if (![self.arrImgList containsObject:add_img]) {
                    [self.arrImgList addObject:add_img];
                }
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                // 非主线程，将UI操作切换到主线程进行
                [self.collection reloadData];
            });

        } else {
            //[XAAlertView toast:@"上传失败，请重新上传"];
        }
        return nil;
    }];

    // [putTask waitUntilFinished];
    // [put cancel];
}

// 随机生成uuid
- (NSString *)uuidString
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid lowercaseString];
}

#pragma mark -- ClickDeleteFeedImageDelegate
-(void)clickDelBtnButtonTag:(NSInteger)buttonTag {
        
    [self.arrImgList removeObjectAtIndex:buttonTag];
    [self.selectImgList removeObjectAtIndex:buttonTag];
    
    if (self.arrImgList.count < 4) {
        if (![self.arrImgList containsObject:add_img]) {
            [self.arrImgList addObject:add_img];
        }
    }
    
    [self.collection reloadData];
}


- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
